package com.ikun.aimian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ikun.aimian.annotation.AuthCheck;
import com.ikun.aimian.common.BaseResponse;
import com.ikun.aimian.common.DeleteRequest;
import com.ikun.aimian.common.ErrorCode;
import com.ikun.aimian.common.ResultUtils;
import com.ikun.aimian.constant.UserConstant;
import com.ikun.aimian.exception.BusinessException;
import com.ikun.aimian.exception.ThrowUtils;
import com.ikun.aimian.model.dto.appcomment.AppCommentAddRequest;
import com.ikun.aimian.model.dto.appcomment.AppCommentQueryRequest;
import com.ikun.aimian.model.entity.AppComment;
import com.ikun.aimian.model.entity.User;
import com.ikun.aimian.model.vo.AppCommentVO;
import com.ikun.aimian.service.AppCommentService;
import com.ikun.aimian.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/app_comment")
@Slf4j
public class AppCommentController {

    @Resource
    private AppCommentService appCommentService;

    @Resource
    private UserService userService;

    /**
     * 新增评论接口（需用户登录）
     *
     */
    @PostMapping("/add")
    public BaseResponse<Long> addComment(@RequestBody AppCommentAddRequest addRequest, HttpServletRequest request) {
        // 校验请求参数是否为空
        ThrowUtils.throwIf(addRequest == null, ErrorCode.PARAMS_ERROR);
        // 构建评论实体对象
        AppComment comment = new AppComment();
        // 设置评论关联的应用ID
        comment.setAppId(addRequest.getAppId());
        // 设置评论的具体内容
        comment.setContent(addRequest.getContent());
        // 从 userService 获取当前登录用户（推荐安全方式）
        User user = userService.getLoginUser(request);
        // 若用户未登录，抛出权限异常
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");
        // 将当前用户ID设置到评论实体中
        comment.setUserId(user.getId());
        // 验证评论内容是否合法有效
        appCommentService.validComment(comment, true);
        // 将评论信息保存到数据库
        boolean result = appCommentService.save(comment);
        // 如果评论保存失败，抛出操作异常
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "评论提交失败");
        // 返回成功响应，包含新创建评论的ID
        return ResultUtils.success(comment.getId());
    }


    /**
     * 根据评论ID获取评论VO
     */
    @GetMapping("/get/vo")
    public BaseResponse<AppCommentVO> getCommentVOById(@RequestParam Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        AppComment comment = appCommentService.getById(id);
        ThrowUtils.throwIf(comment == null, ErrorCode.NOT_FOUND_ERROR, "评论不存在");
        AppCommentVO vo = appCommentService.getCommentVO(comment, request);
        return ResultUtils.success(vo);
    }

    /**
     * 分页查询评论列表（管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<AppComment>> listCommentByPage(@RequestBody AppCommentQueryRequest queryRequest) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        Page<AppComment> commentPage = appCommentService.page(new Page<>(current, size),
                appCommentService.getQueryWrapper(queryRequest));
        return ResultUtils.success(commentPage);
    }

    /**
     * 分页获取当前登录用户的评论列表（用户自己可用）
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<AppCommentVO>> listMyCommentByPage(@RequestBody AppCommentQueryRequest queryRequest,
                                                                HttpServletRequest request) {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");

        // 强制使用当前登录用户的 userId，而不是前端传的
        Long userId = loginUser.getId();

        // 构造分页参数
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();

        // 构造 QueryWrapper，但只查询 userId = 当前登录用户
        // 同时可以根据 queryRequest 里的 appId、时间范围等再做过滤
        QueryWrapper<AppComment> queryWrapper = appCommentService.getQueryWrapper(queryRequest);
        queryWrapper.eq("userId", userId);

        // 分页查询
        Page<AppComment> commentPage = appCommentService.page(new Page<>(current, size), queryWrapper);

        // 转换为 VO，并补充用户信息
        Page<AppCommentVO> voPage = appCommentService.getCommentVOPage(commentPage, request);
        return ResultUtils.success(voPage);
    }

    /**
     * 分页获取某个应用的所有评论（无需管理员权限，仅按 appId 筛选）
     */
    @PostMapping("/list/app")
    public BaseResponse<Page<AppCommentVO>> listCommentByApp(@RequestBody AppCommentQueryRequest queryRequest,
                                                             HttpServletRequest request) {
        // 必须传入 appId
        Long appId = queryRequest.getAppId();
        ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR, "应用ID不能为空");

        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();

        // 只按照 appId 筛选
        QueryWrapper<AppComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("appId", appId);
        queryWrapper.orderByDesc("createTime");

        Page<AppComment> commentPage = appCommentService.page(new Page<>(current, size), queryWrapper);
        Page<AppCommentVO> voPage = appCommentService.getCommentVOPage(commentPage, request);
        return ResultUtils.success(voPage);
    }


    /**
     * 删除评论（仅评论作者或管理员可删除，物理删除）
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 参数校验
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 获取当前登录用户
        User user = userService.getLoginUser(request);
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR, "用户未登录");

        long id = deleteRequest.getId();
        // 查出要删除的评论
        AppComment oldComment = appCommentService.getById(id);
        ThrowUtils.throwIf(oldComment == null, ErrorCode.NOT_FOUND_ERROR, "评论不存在");

        // 判断是否有权限删除：是管理员，或是评论作者本人
        boolean isAdmin = userService.isAdmin(request);
        boolean isOwner = oldComment.getUserId() != null && oldComment.getUserId().equals(user.getId());
        if (!isAdmin && !isOwner) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限删除该评论");
        }

        // 直接物理删除
        boolean result = appCommentService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除评论失败");
        return ResultUtils.success(true);
    }



}
